<template>
  <div class="system-log-container" >
    <vab-query-form>
      <vab-query-form-top-panel>
        <el-form
          :inline="true"
          label-width="60px"
          :model="queryForm"
          @submit.native.prevent
        >
          <el-form-item label="关键词">
            <el-input
              v-model.trim="queryForm.query"
              clearable
              placeholder="请输入关键词"
            />
          </el-form-item>
          <el-form-item label="密码">
            <el-select v-model="queryForm.is_right" clearable placeholder="请选择">
              <el-option label="全部" value="" />
              <el-option label="正确" value="1" />
              <el-option label="错误" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryForm.status" clearable placeholder="请选择">
              <el-option label="全部" value="" />
              <el-option label="处理中" value="1" />
              <el-option label="已完成" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="平台">
            <el-select v-model="queryForm.schoolCode" clearable placeholder="请选择">
              <el-option
                v-for="item in schoolList"
                :key="item.id"
                :label="item.school_name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="queryData">
              查询
            </el-button>
          </el-form-item>
          <el-form-item v-permissions="['Admin']">
            <el-popover placement="bottom" trigger="click" width="500">
              <template #reference>
                <el-button type="primary"> 
                  添加后台任务
                </el-button>
              </template>
              <el-form ref="addJobForm" label-width="80px"  >
                <h3>添加后台任务</h3>
                <el-form-item label="平台">
                  <el-checkbox-group v-model="jobform.schoolCode">
                    <el-checkbox 
                      v-for="item in schoolList"
                      :key="item.id"
                      :label="item.id"
                      name="schoolCode">
                      {{item.school_name}}
                    </el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item label="任务">
                  <el-checkbox-group v-model="jobform.jobTypeArr">
                    <el-checkbox 
                      v-for="(item, index) in typeArr"
                      :key="index"
                      :label="index"
                      name="type">{{item.name}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>

                <el-form-item label="处理未完成">
                  <el-radio-group v-model="jobform.is_only_unfinished">
                    <el-radio label="1">是</el-radio>
                    <el-radio label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="批次">
                  <el-input v-model="jobform.branch" clearable placeholder="请输入批次" />
                </el-form-item>
                <el-form-item label="其他参数">
                  <el-input v-model="jobform.outher" clearable placeholder="其他参数" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="branchAddJob()">
                    提交
                  </el-button>
                </el-form-item>
              </el-form>
            </el-popover>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="xslxInputClick">
              批量导入
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="add">
              新增
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="branchConfirmCourse">
              批量确认用户课程
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="branchConfirmCourseCompeleted">
              批量确认标记完成
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-top-panel>
    </vab-query-form>
    <el-table  v-loading="listLoading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column
        align="center"
        label="ID"
        prop="id"
        show-overflow-tooltip
        width="60px"
      />
      <el-table-column
        align="center"
        label="姓名"
        prop="name"
        show-overflow-tooltip
        width="50"
      />
      <el-table-column
        align="center"
        label="账号"
        prop="username"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="密码"
        prop="password"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="密码？"
        prop="password"
        width="60"
      >
        <template slot-scope="scope">
          <el-tag size="mini" text :type="scope.row.is_right ? 'success' : 'danger'">
            {{scope.row.is_right ? '正确' : '错误'}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="平台"
        prop="school_info.school_name"
        show-overflow-tooltip
        width="120"
      />
      <el-table-column
        align="center"
        label="录入人"
        prop="lururen"
        show-overflow-tooltip
        width="50"
      />
      <el-table-column
        align="center"
        label="科目数"
        prop="course_count"
        show-overflow-tooltip
        width="50"
      />

      <el-table-column
        align="center"
        label="批次"
        prop="branch"
        width="80"
      />
      <el-table-column
        align="center"
        label="任务状况"
        prop="course_count"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <el-progress
            :percentage="scope.row.percentage"            
          />
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="进度"
        show-overflow-tooltip
        width="350"
      >
        <template slot-scope="scope">
            <el-popover
              v-for="(item, index) in scope.row.course_list" :key="index"
              placement="top-start"
              :title="item.courseName + ':' + item.score + ( '--【'+ (item.is_confirm_do == 1 ? '已确认' : '未确认') +'】' )"
              trigger="hover"
              width="300"
              >
                <div v-html="item.course_progress_str"></div>
                <el-button slot="reference" v-if="item.is_confirm_do" circle size="small" :type="item.button_color" >{{item.first_letter}}</el-button>
                <el-button slot="reference" v-else circle size="small" type="info" >{{item.first_letter}}</el-button>
            </el-popover>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="上次更新时间"
        prop="update_time"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <el-tag :type="scope.row.progress_update_time_str.tag_type">{{scope.row.progress_update_time_str.str}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
      align="center"
      label="状态"
      prop="course_count"
      width="60"
    >
      <template slot-scope="scope">
        <el-tag size="mini" :type="scope.row.status == 1 ? 'info' : 'success'" >
          {{scope.row.status == 1 ? '处理中' : '已完成'}}
        </el-tag>
      </template>
    </el-table-column>
      <el-table-column
        align="center"
        fixed="right"
        label="操作"
        prop="lururen"
        width="200"
        >
        <template slot-scope="scope">
          <el-button size="small" type="text" @click="updateUserProgress(scope.row)">更新</el-button>
          <el-button size="small" type="text" @click="userEdit(scope.row)">编辑</el-button>
          <el-button v-if="scope.row.status == 1" size="small" type="text" @click="markAsCompleted(scope.row, 2)">标记完成</el-button>
          <el-button v-if="scope.row.status == 2" size="small" type="text" @click="markAsCompleted(scope.row, 1)">标记处理中</el-button>
          <el-popover v-if="scope.row.confirm_do_count < scope.row.course_list.length" placement="top-start" trigger="hover" :width="300" >
            <p>请确认需要处理的课程:</p>
            <el-form ref="courseForm">
              <el-form-item>
                <el-checkbox-group v-model="scope.row.courseCheckList">
                  <el-row>
                    <block v-for="(course, index) in scope.row.course_list" :key="index" >
                      <el-col v-if="course.is_confirm_do == 0" :span="12">
                        <el-checkbox :key="course.courseId" :label="course.courseId" :name="scope.row.id + 'courses'">{{ course.courseName }}</el-checkbox>
                      </el-col>
                    </block>
                  </el-row>
                </el-checkbox-group>
            </el-form-item> 
            <el-form-item >
              <p>当前已选择{{ scope.row.courseCheckList.length }}科:</p>
                <el-button type="primary" @click="confirmSelectedCourses(scope.row)">确认所选科目</el-button>
              </el-form-item>
            </el-form>
            <template #reference>
              <el-button size="small" type="text">确认科目</el-button>
            </template>
          </el-popover>
          <!-- <el-button size="small" type="text" @click="restartAllJob(scope.row)">重试所有任务</el-button> -->
        </template>
      </el-table-column>
      <template #empty>
        <el-image
          class="vab-data-empty"
          :src="require('@/assets/empty_images/data_empty.png')"
        />
      </template>
    </el-table>
    <!-- <el-popover  ref="coursePopover" v-model="popoverVisible" placement="top" trigger="manual"  width="300" >
      <div v-for="(course, index) in selectedCourseList" :key="index">
        <el-checkbox v-model="selectedCourses" :label="course.id">{{ course.name }}</el-checkbox>
      </div>
      <el-button type="primary" @click="confirmSelectedCourses(scope.row)">确认所选科目</el-button>
    </el-popover> -->
    <el-pagination
      background
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <xslx-input
      ref="xslxInput"
      :field-list="fieldList"
      @successInputData="successInputData"
    />  
    <UnionMemberForm ref="UnionMemberForm" :school-list="schoolList" @fetch-data="fetchData"/>
    </div>

</template>

<script>
  import { getList, addChengkaoJob, config, branchInput, normalChengkaoJob, markStatus, confirmUserDoCourse} from '@/api/unionMember'
  import XslxInput from '@/components/XslxInput/index.vue'
  import UnionMemberForm from './components/UnionMemberForm.vue'
  export default {
    name: 'SystemLog',
    components: { XslxInput , UnionMemberForm},
    data() {
      return {
        list: [],
        listLoading: true,
        dialogTableVisible: false,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        visible: false,
        queryForm: {
          account: '',
          searchDate: '',
          pageNo: 1,
          status: "1",
          pageSize: 20,
        },
        selectedCourses: {
          checkList: [],
        },
        schoolList: [],
        typeArr: {},
        checkList: [],
        jobform: {
          jobTypeArr: [],
          schoolCode: [],
          branch: '',
          
          is_only_unfinished: "0",
          outher: '',
        },
        fieldList: [
          {
            name: '姓名',
            key: 'name',
          },
          {
            name: '登录账号',
            key: 'username',
          },
          {
            name: '登录密码',
            key: 'password',
          },
          {
            name: '录入人',
            key: 'lururen',
          },
          {
            name: '层次',
            key: 'cengci',
          },
          {
            name: '批次',
            key: 'pici',
          },
          {
            name: '专业',
            key: 'zhuanye',
          },
          {
            name: '学习平台',
            key: 'schoolCode',
          },
        ],
        selectedRows: [],
      }
    },
    created() {
      this.fetchData()
      this.fetchConfig();
    },
    methods: {
      showCoursePopover(row) {
      this.selectedCourseList = row.course_list;
      this.selectedCourses = [];
      this.popoverVisible = true;
      this.$nextTick(() => {
        this.$refs.coursePopover.referenceElm = event.target;
      });
    },
    checkListChange(e){
      console.log(e)
    },
    async confirmSelectedCourses(e) {
      console.log('Selected courses:', e);
      this.popoverVisible = false;
      console.log(this.checkList);
      // 在这里添加处理选中科目的逻辑

      var confirmData = [];
      confirmData.push({member_id: e.id, courseIds: e.courseCheckList})

      let { data } = await confirmUserDoCourse({
        confirmData: JSON.stringify(confirmData)
      })
      console.log(data)
      this.fetchData()
      this.$store.dispatch('user/refreshBalance'); // 调用 dispatch 更新余额信息
    },
      xslxInputClick(){
        this.$refs.xslxInput.dialogFormVisible = true
        this.$refs.xslxInput.show()
      },
      userEdit(row){
        this.$refs.UnionMemberForm.showEdit(row)
      },
      add(){
        this.$refs.UnionMemberForm.showEdit()
      },
      async updateUserProgress(user){
        console.log(user)
        this.listLoading = true
        try {
          let {data} = await addChengkaoJob({"type": "unionUpdateCourseProgress", "id": user.id})
          console.log(data)
          this.$message({
            message: '提交更新任务成功',
            type: 'success'
          })
        } catch (error) {
          console.log(error)
        }
        this.listLoading = false
      },
      async restartAllJob(user){
        this.listLoading = true
        try {
          let {data} = await addChengkaoJob({"type": "handleAllJob", "id": user.id})
          this.$message({
            message: '添加所有任务处理逻辑成功',
            type: 'success'
          })
           console.log(data)
        } catch (error) {
          console.log(error)
        }
        this.listLoading = false
      },
      async successInputData(data){
        console.log(data)

        const user_json = JSON.stringify(data)
        console.log(user_json)
        this.$refs.xslxInput.drawer_loading = true
        try {
          await branchInput({ user_json: user_json })
          this.$refs.xslxInput.drawer_loading = false
          this.fetchData()
          this.$refs.xslxInput.dialogFormVisible = false
        } catch (error) {
          this.$refs.xslxInput.drawer_loading = false
          console.log(error)
        }
      },

      async branchConfirmCourseCompeleted(){
        console.log(this.selectedRows)
        if (this.selectedRows.length === 0) {
          this.$message.warning('请选择要确认的用户');
          return;
        }
        // 用的id 存入ids 调用接口提交
        let ids = this.selectedRows.map(row => row.id);
        this.$confirm(`将会标记选中用户的所有任务为完成，是否继续?`, '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            
            let { data } = await markStatus({ ids: ids.join(','), status: 2 });
            console.log(data);
            this.$message.success('批量标记完成成功');
            this.fetchData();
          } catch (error) {
            console.log(error);
            this.$message.error('批量标记完成失败');
          }
        }).catch(() => {
          this.$message.info('已取消批量标记完成');
        });
     
      },

      async branchConfirmCourse() {
        console.log(this.selectedRows)
        if (this.selectedRows.length === 0) {
          this.$message.warning('请选择要确认课程的用户');
          return;
        }
  
        let totalUnconfirmed = 0;
        let confirmData = [];
  
        this.selectedRows.forEach(row => {
          let unconfirmedCourses = row.course_list.filter(course => course.is_confirm_do == 0).map(course => course.courseId);
          if (unconfirmedCourses.length > 0) {
            totalUnconfirmed += unconfirmedCourses.length;
            confirmData.push({ member_id: row.id, courseIds: unconfirmedCourses });
          }
        });
  
        if (totalUnconfirmed === 0) {
          this.$message.info('没有未确认的课程');
          return;
        }
  
        this.$confirm(`将会确认选中用户的所有未确认课程，共有 ${totalUnconfirmed} 科未确认，是否继续?`, '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            let { data } = await confirmUserDoCourse({
              confirmData: JSON.stringify(confirmData)
            });
            console.log(data);
            this.$message.success('批量确认成功');
            this.fetchData();
          } catch (error) {
            console.log(error);
            this.$message.error('批量确认失败');
          }
          this.$store.dispatch('user/refreshBalance'); // 调用 dispatch 更新余额信息
        }).catch(() => {
          this.$message.info('已取消批量确认');
        });
      },
      async branchAddJob(){
        console.log(this.jobform)
        this.listLoading = true
        try {
          let {data} = await normalChengkaoJob(this.jobform)
          console.log(data)
          this.$message({
            message: '提交任务成功',
            type: 'success'
          })
          this.$refs["addJobForm"].resetFields();
        } catch (error) {
          console.log(error)
        }
        this.listLoading = false
      },
      async markAsCompleted(user, status) {
        try {
          await markStatus({ ids: user.id, status: status });
          this.$message({
            message: '标记完成成功',
            type: 'success'
          });
          
          this.fetchData();
        } catch (error) {
          console.log(error);
        }
      },
      async fetchConfig(command){
        try {
          let {data} = await config({"type": command})
          this.schoolList = data.schoolList;
          this.typeArr = data.typeArr;
          console.log(data)

        } catch (error) {
          console.log(error)
        }
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNo = val
        this.fetchData()
      },
      queryData() {
        this.queryForm.pageNo = 1
        this.fetchData()
      },
      async fetchData() {
        this.listLoading = true
        const {
          data: { list, page },
        } = await getList(this.queryForm)
        list.forEach(element => {
          element.courseCheckList = []
          var confirm_do_count = 0;
          element.course_list.forEach(course => {
            if (course.is_confirm_do == 1) {
              confirm_do_count++;
            }
            element.courseCheckList.push(course.courseId)
          });
          element.confirm_do_count = confirm_do_count;
        });
        this.list = list
        this.total = page.total
        this.listLoading = false
      },
      handleSelectionChange(val) {
        this.selectedRows = val;
      },
    },
  }
</script>

<style>

.el-button--small.is-circle {
  padding: 5px !important;
}

.el-button--small {
  font-size: 9px !important;
}
.el-button {
  margin-left: 4px !important;
}
.el-progress__text{
  font-size: 11px !important;
}
.el-table .cell {
  box-sizing: border-box;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
  word-break: break-all;
  line-height: 1 !important; /* 调整行高 */
  padding-left: 3px !important; /* 调整左边距 */
  padding-right: 3px !important; /* 调整右边距 */
  font-size: 11px !important; /* 调整字体大小 */
}
.el-tag{
  font-size: 11px !important;
}
</style>

